var PORT = 8000;
var ADDR = "127.0.0.1";

var http = require('http');
var url=require('url');
var fs=require('fs');
var querystring=require('querystring');
var mine=require('./mine').types;
var path=require('path');
var markdown=require('./lib/markdown/markdown');
var prettify=require('./lib/markdown/prettify-nodejs');
var prettifyInline = true;

var parseUrl_ = function(urlString) {
  var parsed = url.parse(urlString);
  parsed.pathname = url.resolve('/', parsed.pathname);
  return url.parse(url.format(parsed), true);
};

var code2Html = function(fileContent){
	fileContent = fileContent.replace(/<p><br><\/p><\/br>/g,'');
	fileContent = '    '+fileContent.replace(/\n/g,'    ');
	fileContent = markdown.toHTML(fileContent);
	//console.log(fileContent);
	fileContent = fileContent.replace(/<pre><code>([\w\W]*?)<\/code><\/pre>/g, function(str, p1) {
		if(prettifyInline) {
			p1 = p1.replace(/&#39;/g, "'");
			p1 = prettify.prettyPrintOne(p1);
		}
		return p1;//'<pre class="prettyprint">' + p1 + '</pre>';
	});
	return '<pre><code class="java">'+ fileContent +'</code></pre>';
}

var server = http.createServer(function(request, response) {
	request.url = parseUrl_(request.url);
    var pathname = ('./' + request.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
		return String.fromCharCode(parseInt(hex, 16));
	});
    //var realPath = path.join("assets", pathname);
    var ext = path.extname(pathname);
    ext = ext ? ext.slice(1) : 'unknown';
	pathname = './'+ pathname;
    fs.exists(pathname, function (exists) {
        if (!exists) {
			console.log("ERR[404] "+ pathname);
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(pathname, "binary", function (err, file) {
                if (err) {
					console.log("ERR[500] "+ pathname);
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
					console.log("ERR[200] "+ pathname);
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType+';charset=UTF-8'
                    });
					var postData='';
					request.addListener("data", function(postDataChunk) { 
						postData += postDataChunk;
					}); 
					var text = querystring.parse(postData).code || '';
					try {
						file = file.replace('${codeText}', text);
						file = file.replace('${code}', text == '' ? '' : code2Html(text));
						response.write(file);
					} catch(e) {
						response.write(e.message);
					}
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT, ADDR);
console.log("Server start "+ ADDR +":"+ PORT);